package com.linkai.JUC._12_forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * @Description: 测试类
 *                3种方法分别进行累加求和计算
 *                1. 普通
 *                2. ForkJoin
 *                3. 并行流
 * @Author: 林凯
 * @Date: 2021/10/25 18:50
 */
public class Test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        test01();
        test02();
        test03();
    }

    // 普通程序员; 时间：614
    public static void test01() {
        long sum = 0L;
        long start = System.currentTimeMillis();
        for (long i = 1; i <= 10_0000_0000; i++) {
            sum += i;
        }
        long end = System.currentTimeMillis();
        System.out.println("普通：sum = " + sum + " 时间 " + (end - start));
    }


    // 会使用 ForkJoin
    public static void test02() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinDemo(1L, 10_0000_0000L);
        ForkJoinTask<Long> submit = forkJoinPool.submit(task);// 提交任务，会有结果
        Long sum = submit.get();
        long end = System.currentTimeMillis();
        System.out.println("ForkJoin：sum = " + sum + " 时间 " + (end - start));

    }

    // 并行流
    public static void test03() {
        long start = System.currentTimeMillis();
        // Stream 并行流
        /*
            range 和 rangeClosed 区别：
            左右都是开区间：range    ( )
            左开右闭：rangeClosed   ( ]
        * */
        long sum = LongStream.rangeClosed(1L, 10_0000_0000L).parallel().reduce(0, Long::sum);
        long end = System.currentTimeMillis();
        System.out.println("并行流：sum = " + sum + " 时间 " + (end - start));
    }
}
